package ro.peoplecentric.ctc.common;


import static ro.peoplecentric.ctc.common.CtcCommonResources.FAILED_UNIT_TEST_RUN_KEY;
import static ro.peoplecentric.ctc.common.CtcCommonResources.START_UNIT_TEST_KEY;
import static ro.peoplecentric.ctc.common.CtcCommonResources.getMessage;

import org.apache.commons.logging.Log;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

/**
 * Logs information about start/stop/failed test execution.
 * @author Vitalie Svet
 * @since  17/080/2013
 */
public class CtcCommonTestLoggerWatcher extends TestWatcher {

	private static final String TEST_DELIMITER = " - ";

	private Log logger;

	CtcCommonTestLoggerWatcher(Log logger) {
		this.logger = logger;
	}

	/**
	 * Logs start test method message.
	 */
	@Override
	protected void starting(Description description) {
		super.starting(description);
		logger.info(getMessage(START_UNIT_TEST_KEY, getTestName(description)));
	}

	/**
	 * Logs failed test message information.
	 */
	protected void failed(Throwable e, Description description) {
		super.failed(e, description);
		logger.error(getMessage(FAILED_UNIT_TEST_RUN_KEY,
				getTestName(description)));
		logger.error(e.getLocalizedMessage());
	};

	/**
	 * Builds run test name.
	 * @param description
	 * @return
	 */
	private String getTestName(Description description) {
		StringBuilder builder = new StringBuilder();
		builder.append(description.getTestClass().getName());
		builder.append(TEST_DELIMITER);
		builder.append(description.getMethodName());
		return builder.toString();
	}

}
